//
//  NewWebviewPluginController.m
//  BaiduTravel
//
//  Created by jiedan chen on 12-6-25.
//  Copyright (c) 2012年 Baidu. All rights reserved.
//

#import "NewWebviewPluginController.h"
#import "MBProgressHUD.h"
#import "NSArray+EX.h"
#import "NSString+NSString_Ex_.h"
#import "UIColor-Expanded.h"
#import "GloableEngineService.h"
#import "AppDelegate.h"

@interface NewWebviewPluginController ()

@end


#define kSourceType         @"topic"



@implementation NewWebviewPluginController
@synthesize myWebview;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id) initWithUrl:(NSURL*)url
{
    self = [super init];
    if (self) {
        requestURL = [[NSURLRequest requestWithURL:url] retain];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [self.myWebview stopLoading];
    myWebview.delegate = nil;
    self.myWebview = nil;
    [showBtn release]; showBtn = nil;
    [toolBar release]; toolBar = nil;
    [backBtn release]; backBtn = nil;
    [forwardBtn release]; forwardBtn = nil;
}

-(void) dealloc
{
    [requestURL release];
    requestURL = nil;
    [myWebview stopLoading];
    myWebview.delegate = nil;
    [myWebview release];
    [showBtn release];
    [toolBar     release];
    [backBtn release];
    [forwardBtn release];
    [super dealloc];
}



-(void) loadView
{
    [super loadView];
    self.navigationController.navigationBarHidden = YES;
    myWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-20-50)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0) {
        myWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, UIScreenHeight-20-50)];
    }
    myWebview.delegate = self;

    [self.view addSubview:myWebview];
    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:44
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    [self.view addSubview:_progressHub];
    _progressHub.labelText = @"加载中...";
    [_progressHub show:YES];
    
    [myWebview loadRequest:requestURL];
    myWebview.scalesPageToFit = YES;
    for (UIView *subView in myWebview.subviews) {
        if ([subView isKindOfClass:[UIScrollView class]]) {
            
            UIScrollView *scrollView = (UIScrollView*)subView;
            scrollView.delegate = self;
        }
    }
    
    
    [self createToolBar];
    [self createTheShowBarButton];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.delegate = self;
    [self.myWebview addGestureRecognizer:singleTap];

    [singleTap release];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{  
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    myWebview.frame = CGRectMake(0, 0, 320, UIScreenHeight-20-50);
}



- (void) createToolBar 
{
    toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, UIScreenHeight-20-50, 320, 50)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, UIScreenHeight-50, 320, 50)];
    }
    toolBar.backgroundColor = [UIColor colorWithHex:0xff4e4e4e];
//    UIImageView *backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"webviewtoolbar.png"]];
//    [toolBar addSubview:backImage];
//    [backImage release];
    
    backBtn = [[UIButton alloc] initWithFrame:CGRectMake(1, 3, 77, 44)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"webview_back.png"] forState:UIControlStateNormal];
       [backBtn setBackgroundImage:[UIImage imageNamed:@"webview_back_down.png"] forState:UIControlStateHighlighted]; 
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:backBtn];
    
    
    forwardBtn = [[UIButton alloc] initWithFrame:CGRectMake(81, 3, 77, 44)];
    [forwardBtn setBackgroundImage:[UIImage imageNamed:@"webview_forward.png"] forState:UIControlStateNormal];
    [forwardBtn setBackgroundImage:[UIImage imageNamed:@"webview_forward_down.png"] forState:UIControlStateHighlighted]; 
    [forwardBtn addTarget:self action:@selector(forward) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:forwardBtn];
    
    
    UIButton *refreshBtn = [[UIButton alloc] initWithFrame:CGRectMake(161, 3, 77, 44)];
    [refreshBtn setBackgroundImage:[UIImage imageNamed:@"webview_refresh.png"] forState:UIControlStateNormal];
    [refreshBtn setBackgroundImage:[UIImage imageNamed:@"webview_refresh_down.png"] forState:UIControlStateHighlighted]; 
    [refreshBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:refreshBtn];
    [refreshBtn release];
    
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(241, 3, 77, 44)];
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"webview_close.png"] forState:UIControlStateNormal];
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"webview_close_down.png"] forState:UIControlStateHighlighted]; 
    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:closeBtn];
    [closeBtn release];
    
    //    [toolBar setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:toolBar];
    
}

-(void) createTheShowBarButton
{
    showBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, UIScreenHeight-20-100, 50, 50)];
    [showBtn setBackgroundImage:[UIImage imageNamed:@"toolbar_extend.png"] forState:UIControlStateNormal];
    [showBtn setBackgroundImage:[UIImage imageNamed:@"toolbar_extend_down.png"] forState:UIControlStateHighlighted]; 
    [showBtn addTarget:self action:@selector(showBar) forControlEvents:UIControlEventTouchUpInside];
    showBtn.hidden = YES;
    [self.view addSubview:showBtn];
}

-(void) showBar
{
    toolBar.hidden = NO;
    showBtn.hidden = YES;
    
}

-(void) forward
{
	[self.myWebview goForward];
	[self refreshToolBarButtons];
}

-(void) back
{
    if (myWebview.canGoBack) {
        [self.myWebview goBack];
        [self refreshToolBarButtons];
    }else {
        [self close];
    }

}

-(void) refresh {
	[self.myWebview reload];
}

-(void) close
{
    [myWebview stopLoading];
    myWebview.delegate = nil;
    [myWebview release];
    myWebview = nil;
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:NO];
}

-(void) refreshToolBarButtons
{
    forwardBtn.enabled = myWebview.canGoForward;
//	backBtn.enabled = myWebview.canGoBack;
}


//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
//}

#pragma 
#pragma mark webview delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //修改服务器页面的meta的值，让webview 不能左右滚动  
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];  
    [webView stringByEvaluatingJavaScriptFromString:meta]; 
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
    [self refreshToolBarButtons];
   
    

}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
    
    [self refreshToolBarButtons];
}

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([GloableEngineService sharedInstance].netWorkStatus == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        return NO;
    }
    
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

- (void) singleTap:(UITapGestureRecognizer*)gesture {
    // handle event
//    toolBar.hidden = YES;
//    showBtn.hidden = NO;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//       toolBar.hidden = YES;
//       showBtn.hidden = NO;  
}

@end
